/*
 * @lc app=leetcode id=208 lang=cpp
 *
 * [208] Implement Trie (Prefix Tree)
 */
class Trie {
    struct Node {
        Node **next;
        int cap;
        bool mark;
        char val;

        Node(char val, int cap = 26) : val(val) {
            this->next = new Node*[cap]{NULL};
            this->mark = false;
        }
    };
public:
    /** Initialize your data structure here. */
    Node *root;
    Trie() {
        root = new Node('\0');
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        int idx = 0;
        Node *node = root;
        for (auto c : word) {
            idx = c - 'a';
            if (!node->next[idx]) {
                node->next[idx] = new Node(c);
            } 
            node = node->next[idx];
        }
        node->mark = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        Node *node = root;
        int idx = 0;
        for (auto c:word) {
            idx = c-'a';
            if (!node->next[idx]) {
                return false;
            }
            node = node->next[idx];
        }
        return node->mark;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        Node *node = root;
        int idx = 0;
        for (auto c : prefix) {
            idx = c-'a';
            if (!node->next[idx]) {
                return false;
            }
            node = node->next[idx];
        }       
        return true;
    }
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */

